<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="买家" prop="buyerId">
        <el-select v-model="queryParams.buyerId" placeholder="请选择买家" clearable @keyup.enter.native="handleQuery">
          <el-option
            v-for="user in userList"
            :key="user.id"
            :label="user.nickname || user.openid"
            :value="user.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="卖家" prop="sellerId">
        <el-select v-model="queryParams.sellerId" placeholder="请选择卖家" clearable @keyup.enter.native="handleQuery">
          <el-option
            v-for="user in userList"
            :key="user.id"
            :label="user.nickname || user.openid"
            :value="user.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="关联车辆" prop="carId">
        <el-select v-model="queryParams.carId" placeholder="请选择车辆" clearable @keyup.enter.native="handleQuery">
          <el-option
            v-for="car in carList"
            :key="car.id"
            :label="car.modelName + ' - ' + car.carCode"
            :value="car.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="定金金额" prop="depositAmount">
        <el-input
          v-model="queryParams.depositAmount"
          placeholder="请输入定金金额"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单总金额" prop="totalAmount">
        <el-input
          v-model="queryParams.totalAmount"
          placeholder="请输入订单总金额"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="支付时间" prop="payTime">
        <el-date-picker clearable
          v-model="queryParams.payTime"
          type="date"
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
          placeholder="请选择支付时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="取消原因" prop="cancelReason">
        <el-input
          v-model="queryParams.cancelReason"
          placeholder="请输入取消原因"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['car:order:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['car:order:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['car:order:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['car:order:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单ID" align="center" prop="id" />
      <el-table-column label="订单编号" align="center" prop="orderNo" />
      <el-table-column label="买家" align="center" prop="buyerId">
        <template slot-scope="scope">
          <span>{{ getBuyerName(scope.row.buyerId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="卖家" align="center" prop="sellerId">
        <template slot-scope="scope">
          <span>{{ getSellerName(scope.row.sellerId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="关联车辆" align="center" prop="carId">
        <template slot-scope="scope">
          <span>{{ getCarName(scope.row.carId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="定金金额" align="center" prop="depositAmount" />
      <el-table-column label="订单总金额" align="center" prop="totalAmount" />
      <el-table-column label="订单状态" align="center" prop="orderStatus">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.orderStatus === 1" type="warning">待付定金</el-tag>
          <el-tag v-else-if="scope.row.orderStatus === 2" type="primary">待付全款</el-tag>
          <el-tag v-else-if="scope.row.orderStatus === 3" type="info">待交付</el-tag>
          <el-tag v-else-if="scope.row.orderStatus === 4" type="success">已完成</el-tag>
          <el-tag v-else-if="scope.row.orderStatus === 5" type="danger">已取消</el-tag>
          <span v-else>{{ scope.row.orderStatus }}</span>
        </template>
      </el-table-column>
      <el-table-column label="支付时间" align="center" prop="payTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.payTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="取消原因" align="center" prop="cancelReason" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['car:order:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['car:order:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改购车订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="订单编号" prop="orderNo">
              <el-input v-model="form.orderNo" placeholder="系统自动生成" readonly>
                <el-button slot="append" icon="el-icon-refresh" @click="refreshOrderNo">重新生成</el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订单状态" prop="orderStatus">
              <el-select v-model="form.orderStatus" placeholder="请选择订单状态">
                <el-option label="待付定金" :value="1"></el-option>
                <el-option label="待付全款" :value="2"></el-option>
                <el-option label="待交付" :value="3"></el-option>
                <el-option label="已完成" :value="4"></el-option>
                <el-option label="已取消" :value="5"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="买家" prop="buyerId">
              <el-select v-model="form.buyerId" placeholder="请选择买家" filterable>
                <el-option
                  v-for="user in userList"
                  :key="user.id"
                  :label="user.nickname || user.openid"
                  :value="user.id">
                  <span style="float: left">{{ user.nickname || user.openid }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ user.phone }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="卖家" prop="sellerId">
              <el-select v-model="form.sellerId" placeholder="请选择卖家" filterable>
                <el-option
                  v-for="user in userList"
                  :key="user.id"
                  :label="user.nickname || user.openid"
                  :value="user.id">
                  <span style="float: left">{{ user.nickname || user.openid }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ user.phone }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="关联车辆" prop="carId">
          <el-select v-model="form.carId" placeholder="请选择车辆" filterable @change="onCarChange">
            <el-option
              v-for="car in carList"
              :key="car.id"
              :label="car.modelName + ' - ' + car.carCode"
              :value="car.id">
              <div style="display: flex; justify-content: space-between;">
                <span>{{ car.modelName }}</span>
                <span style="color: #8492a6; font-size: 13px">{{ car.carCode }} - ¥{{ car.price }}</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="定金金额" prop="depositAmount">
              <el-input-number v-model="form.depositAmount" :precision="2" :min="0" :max="999999" placeholder="请输入定金金额" style="width: 100%">
                <template slot="append">元</template>
              </el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订单总金额" prop="totalAmount">
              <el-input-number v-model="form.totalAmount" :precision="2" :min="0" :max="9999999" placeholder="请输入订单总金额" style="width: 100%">
                <template slot="append">元</template>
              </el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="支付时间" prop="payTime">
              <el-date-picker clearable
                v-model="form.payTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择支付时间"
                style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.orderStatus === 5">
            <el-form-item label="取消原因" prop="cancelReason">
              <el-input v-model="form.cancelReason" placeholder="请输入取消原因" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注信息" prop="remark" v-if="form.orderStatus === 5">
          <el-input v-model="form.cancelReason" type="textarea" :rows="3" placeholder="请详细说明取消原因..." />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listorder, getorder, delorder, addorder, updateorder, getFormData, generateOrderNo } from "@/api/car/order"

export default {
  name: "order",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用 
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 购车订单（订单页、订单详情）表格数据
      orderList: [],
      // 用户列表
      userList: [],
      // 车辆列表
      carList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNo: null,
        buyerId: null,
        sellerId: null,
        carId: null,
        depositAmount: null,
        totalAmount: null,
        orderStatus: null,
        payTime: null,
        cancelReason: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        orderNo: [
          { required: true, message: "订单编号不能为空", trigger: "blur" }
        ],
        buyerId: [
          { required: true, message: "请选择买家", trigger: "change" },
          { validator: this.validateBuyerSeller, trigger: "change" }
        ],
        sellerId: [
          { required: true, message: "请选择卖家", trigger: "change" },
          { validator: this.validateBuyerSeller, trigger: "change" }
        ],
        carId: [
          { required: true, message: "请选择关联车辆", trigger: "change" }
        ],
        depositAmount: [
          { required: true, message: "定金金额不能为空", trigger: "blur" },
          { type: 'number', min: 0.01, message: "定金金额必须大于0", trigger: "blur" },
          { validator: this.validateDepositAmount, trigger: "blur" }
        ],
        totalAmount: [
          { required: true, message: "订单总金额不能为空", trigger: "blur" },
          { type: 'number', min: 0.01, message: "订单总金额必须大于0", trigger: "blur" }
        ],
        orderStatus: [
          { required: true, message: "请选择订单状态", trigger: "change" }
        ],
        cancelReason: [
          { validator: this.validateCancelReason, trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.loadFormData()
  },
  methods: {
    /** 加载表单数据 */
    loadFormData() {
      getFormData().then(response => {
        this.userList = response.data.userList || []
        this.carList = response.data.carList || []
      })
    },
    /** 查询购车订单（订单页、订单详情）列表 */
    getList() {
      this.loading = true
      listorder(this.queryParams).then(response => {
        this.orderList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 根据用户ID获取用户名称 */
    getBuyerName(buyerId) {
      const user = this.userList.find(u => u.id === buyerId)
      return user ? (user.nickname || user.openid) : buyerId
    },
    /** 根据用户ID获取卖家名称 */
    getSellerName(sellerId) {
      const user = this.userList.find(u => u.id === sellerId)
      return user ? (user.nickname || user.openid) : sellerId
    },
    /** 根据车辆ID获取车辆名称 */
    getCarName(carId) {
      const car = this.carList.find(c => c.id === carId)
      return car ? (car.modelName + ' - ' + car.carCode) : carId
    },
    /** 重新生成订单编号 */
    refreshOrderNo() {
      generateOrderNo().then(response => {
        console.log('重新生成API响应:', response)
        // 若依框架返回格式：{code: 200, msg: "操作成功", data: "订单编号"}
        const orderNo = response.data || response
        this.form.orderNo = orderNo
        this.$message.success('订单编号已重新生成')
        console.log('订单编号生成成功:', orderNo)
        // 强制更新视图
        this.$forceUpdate()
      }).catch(error => {
        console.error('生成订单编号失败:', error)
        // 如果API调用失败，使用前端生成的订单编号
        const timestamp = new Date().toISOString().replace(/[-T:.Z]/g, '').slice(0, 14)
        const randomNum = String(Math.floor(Math.random() * 1000000)).padStart(6, '0')
        const orderNo = 'ORDER' + timestamp + randomNum
        this.form.orderNo = orderNo
        this.$message.warning('使用本地生成的订单编号')
        console.log('使用本地订单编号:', orderNo)
        // 强制更新视图
        this.$forceUpdate()
      })
    },
    /** 车辆选择变化事件 */
    onCarChange(carId) {
      const car = this.carList.find(c => c.id === carId)
      if (car) {
        // 自动填充车辆价格到订单总金额
        this.form.totalAmount = car.price
        // 建议定金为车辆价格的10%
        this.form.depositAmount = Math.round(car.price * 0.1)
        
        // 自动设置卖家
        this.form.sellerId = car.sellerId
      }
    },
    /** 验证买家和卖家不能相同 */
    validateBuyerSeller(rule, value, callback) {
      if (this.form.buyerId && this.form.sellerId && this.form.buyerId === this.form.sellerId) {
        callback(new Error('买家和卖家不能是同一人'))
      } else {
        callback()
      }
    },
    /** 验证定金金额 */
    validateDepositAmount(rule, value, callback) {
      if (this.form.totalAmount && value > this.form.totalAmount) {
        callback(new Error('定金金额不能超过订单总金额'))
      } else {
        callback()
      }
    },
    /** 验证取消原因 */
    validateCancelReason(rule, value, callback) {
      if (this.form.orderStatus === 5 && (!value || value.trim() === '')) {
        callback(new Error('订单状态为已取消时，必须填写取消原因'))
      } else {
        callback()
      }
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orderNo: '',
        buyerId: null,
        sellerId: null,
        carId: null,
        depositAmount: null,
        totalAmount: null,
        orderStatus: 1,
        payTime: null,
        cancelReason: null,
        createTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加购车订单"
      
      // 先使用本地生成的订单编号，确保界面有内容显示
      const localTimestamp = new Date().toISOString().replace(/[-T:.Z]/g, '').slice(0, 14)
      const localRandomNum = String(Math.floor(Math.random() * 1000000)).padStart(6, '0')
      const localOrderNo = 'ORDER' + localTimestamp + localRandomNum
      this.form.orderNo = localOrderNo
      this.form.orderStatus = 1
      
      // 延迟执行，尝试从后端获取订单编号
      this.$nextTick(() => {
        generateOrderNo().then(response => {
          console.log('API响应完整数据:', response)
          console.log('response.data:', response.data)
          console.log('response 类型:', typeof response)
          
          // 若依框架返回格式处理
          let orderNo = null
          if (response && typeof response === 'object') {
            if (response.data) {
              orderNo = response.data
            } else if (response.code === 200 && response.msg) {
              // 可能数据在其他字段
              orderNo = response.result || response.content || localOrderNo
            }
          } else if (typeof response === 'string') {
            orderNo = response
          }
          
          if (orderNo && orderNo !== localOrderNo) {
            this.form.orderNo = orderNo
            console.log('新增订单，API生成编号:', orderNo)
            this.$forceUpdate()
          } else {
            console.log('新增订单，使用本地编号:', localOrderNo)
          }
        }).catch(error => {
          console.error('生成订单编号失败:', error)
          console.log('新增订单，保持本地编号:', localOrderNo)
        })
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getorder(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改购车订单"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 额外的业务逻辑验证
          if (this.form.buyerId === this.form.sellerId) {
            this.$modal.msgError("买家和卖家不能是同一人")
            return
          }
          
          if (this.form.depositAmount > this.form.totalAmount) {
            this.$modal.msgError("定金金额不能超过订单总金额")
            return
          }
          
          if (this.form.orderStatus === 5 && (!this.form.cancelReason || this.form.cancelReason.trim() === '')) {
            this.$modal.msgError("订单状态为已取消时，必须填写取消原因")
            return
          }
          
          // 处理表单数据，确保日期格式正确
          const formData = { ...this.form }
          
          // 如果支付时间为空字符串，设置为null
          if (formData.payTime === '' || formData.payTime === undefined) {
            formData.payTime = null
          }
          
          console.log('提交的表单数据:', formData)
          
          const loading = this.$loading({
            lock: true,
            text: '处理中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          
          if (formData.id != null) {
            updateorder(formData).then(response => {
              loading.close()
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            }).catch(error => {
              loading.close()
              console.error('修改错误详情:', error)
              this.$modal.msgError("修改失败：" + (error.msg || error.message || "未知错误"))
            })
          } else {
            addorder(formData).then(response => {
              loading.close()
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            }).catch(error => {
              loading.close()
              console.error('新增错误详情:', error)
              this.$modal.msgError("新增失败：" + (error.msg || error.message || "未知错误"))
            })
          }
        } else {
          this.$modal.msgError("请检查表单填写是否正确")
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除购车订单（订单页、订单详情）编号为"' + ids + '"的数据项？').then(function() {
        return delorder(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('car/order/export', {
        ...this.queryParams
      }, `order_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style scoped>
.el-input-number {
  width: 100%;
}

.el-select {
  width: 100%;
}

.el-form-item {
  margin-bottom: 18px;
}

.el-dialog__body {
  padding: 20px 20px 10px 20px;
}

.el-tag {
  font-weight: 500;
}

/* 表格中的金额显示 */
.el-table .cell {
  word-break: normal;
}

/* 订单状态标签样式 */
.el-tag.el-tag--warning {
  background-color: #fdf6ec;
  border-color: #faecd8;
  color: #e6a23c;
}

.el-tag.el-tag--primary {
  background-color: #ecf5ff;
  border-color: #d9ecff;
  color: #409eff;
}

.el-tag.el-tag--info {
  background-color: #f4f4f5;
  border-color: #e9e9eb;
  color: #909399;
}

.el-tag.el-tag--success {
  background-color: #f0f9ff;
  border-color: #c6f7e9;
  color: #67c23a;
}

.el-tag.el-tag--danger {
  background-color: #fef0f0;
  border-color: #fbc4c4;
  color: #f56c6c;
}

/* 表单布局优化 */
.el-row {
  margin-bottom: 0;
}

.el-col {
  padding-right: 10px;
  padding-left: 10px;
}

/* 只读输入框样式 */
.el-input.is-disabled .el-input__inner {
  background-color: #f8f9fa;
  border-color: #e9ecef;
  color: #495057;
}

/* 下拉选项样式优化 */
.el-select-dropdown__item {
  height: auto;
  line-height: 1.4;
  padding: 8px 20px;
}
</style>
